//
//  CercaMapViewController.m
//  FinApp
//
//  Created by Victor Leandro Fernandez Rodrigo on 11/11/11.
//  Copyright (c) 2011 FIB-Fàcultat d'informàtica de Barcelona. All rights reserved.
//

#import "CercaMapViewController.h"
#import "ListFlat.h"
#import "FlatAnnotation.h"
#import "Defines.h"
#import "CercaViewController.h"
#import "LocationManager.h"

@implementation CercaMapViewController

@synthesize mapView = _mapView;
@synthesize places = _places;
@synthesize markers = _markers;
@synthesize parentVC = _parentVC;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self loadMap];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)loadMap {
	double minLat = 0, maxLat = 0, minLon = 0, maxLon = 0;
	if ([[_parentVC flats] count] > 0) {
		minLat = maxLat = [[[_parentVC flats] objectAtIndex:0] latitude];
		minLon = maxLon = [[[_parentVC flats] objectAtIndex:0] longitude];
	}
	
	[_mapView removeAnnotations:_mapView.annotations];
	if (_markers == nil) _markers = [[NSMutableArray alloc] init];
	[_markers removeAllObjects];
	
	for (ListFlat *flat in [_parentVC flats]) {
        
		int latitude = [flat latitude];
		int longitude = [flat longitude];
		if (latitude == 0  && longitude == 0)
			break;
		CLLocationCoordinate2D coords;
		coords.latitude = [flat latitude];
		coords.longitude = [flat longitude];
		if(minLat > coords.latitude || minLat == 0)
			minLat = coords.latitude;
		else if (maxLat < coords.latitude || maxLat == 0)
			maxLat = coords.latitude;
		if(minLon > coords.longitude || minLon == 0)
			minLon = coords.longitude;
		else if (maxLon < coords.longitude|| maxLon == 0)
			maxLon = coords.longitude;
		
		CLLocationCoordinate2D location;
		location.latitude = flat.latitude;
		location.longitude = flat.longitude;
		FlatAnnotation *annotation = [[FlatAnnotation alloc] initWithCoordinate:location title:[flat street] andSubtitle:[flat city]];
		[annotation setFlatTag:[[_parentVC flats] indexOfObject:flat]];
		[_mapView addAnnotation:annotation];
		[_markers addObject:annotation];
		[annotation release];
	}
	
	MKCoordinateSpan span = MKCoordinateSpanMake(10,10);
	CLLocationCoordinate2D myLocation;
	myLocation.latitude  = [[LocationManager sharedInstance] myLocation].coordinate.latitude;
	myLocation.longitude = [[LocationManager sharedInstance] myLocation].coordinate.longitude;
	
	if ([[_parentVC flats] count] == 0 && abs(myLocation.latitude) < 0.001 && abs(myLocation.longitude) < 0.001)
	{
		DLog(@"Map. Case: 0 flats and noLocation.");
		myLocation.latitude = 40.4171;
		myLocation.longitude = -3.6994;
		span.latitudeDelta = 6;
		span.longitudeDelta = 7;
	}
	else if([[_parentVC flats] count] == 1) {
		DLog(@"Map. Case: 1 flats.");
		span.latitudeDelta = 0.02;
		span.longitudeDelta = 0.02;
		myLocation.latitude = [[[_parentVC flats] objectAtIndex:0] latitude];
		myLocation.longitude = [[[_parentVC flats] objectAtIndex:0] longitude];
	}
	else {
		DLog(@"Map. Case: More than a flats.");
		span.latitudeDelta = maxLat - minLat;
		span.longitudeDelta = maxLon - minLon;
		if (span.latitudeDelta == 0 || span.longitudeDelta == 0) {
			span.latitudeDelta = 0.02;
			span.longitudeDelta = 0.02;
		}
		else {
			myLocation.latitude = span.latitudeDelta/2 + minLat;
			myLocation.longitude = span.longitudeDelta/2 + minLon;
		}
	}
	
	MKCoordinateRegion myRegion = MKCoordinateRegionMake(myLocation, span);
	[_mapView regionThatFits:myRegion];
	
	@try {
		[_mapView setRegion:myRegion animated:YES];
		[_mapView setShowsUserLocation:YES];
	}
	@catch (NSException * e) {
		DLog(@"Warning: Invalid region!");
	}
	
	
	if ([_mapView respondsToSelector:@selector(reloadInputViews)]) {
		[_mapView reloadInputViews];
	}
	else {
		[_mapView setNeedsDisplay];
	}		
}

#pragma mark -
#pragma mark MKMapViewDelegate protocol

- (MKAnnotationView *)mapView:(MKMapView *)mv viewForAnnotation:(id <MKAnnotation>)annotation {
	
	if (mv.userLocation == annotation ) {
		return nil;
	}
	
	FlatAnnotation *delegate = annotation;
	ListFlat *flat = [[_parentVC flats] objectAtIndex:[delegate flatTag]];
	MKAnnotationView *annView = nil;
	
	annView = (MKAnnotationView*)[_mapView dequeueReusableAnnotationViewWithIdentifier:@"flatLoc"];
	if (annView == nil) {
		annView = [[[MKAnnotationView alloc] initWithAnnotation:delegate reuseIdentifier:@"flatLoc"] autorelease];
	}
	annView.canShowCallout = YES;
	
	// Create the right view: 2 labels and a disclosure button, dynamic sizing
	UIView *rightV = [[UIView alloc] init];
	
	UILabel *distLabel = [[UILabel alloc] init];
	[distLabel setBackgroundColor:[UIColor clearColor]];
	[distLabel setTextColor:[UIColor whiteColor]];
	
	if (flat.distance > 1000) {
		[distLabel setText:[NSString stringWithFormat:@"(%.1f km)",flat.distance/1000]];
	}
	else {
		[distLabel setText:[NSString stringWithFormat:@"(%.0f m)",flat.distance]];
	}
	
	
	CGSize size = [distLabel.text sizeWithFont:distLabel.font];
    NSInteger priceWidth = 0;
	CGRect frame = CGRectMake(5, -5, size.width, size.height); // Magic numbers ahead for precise positioning of the elements
	CGRect viewFrame = CGRectMake(0, 0, size.width + 35, 60);
	[distLabel setFrame:frame];
	[rightV addSubview:distLabel];
	[distLabel release];
	UILabel *priceLabel = [[UILabel alloc] init];
    [priceLabel setBackgroundColor:[UIColor clearColor]];
	[priceLabel setTextColor:[UIColor whiteColor]];
	[priceLabel setText:[NSString stringWithFormat:@"%.0f €",flat.price]];
	size = [priceLabel.text sizeWithFont:priceLabel.font];
	frame = CGRectMake(5, 15, size.width, size.height);
	[priceLabel setFrame:frame];
	[rightV addSubview:priceLabel];
    priceWidth += size.width;
	
    
    
    if (viewFrame.size.width < priceWidth + 35) {
        viewFrame = CGRectMake(viewFrame.origin.x, viewFrame.origin.y, priceWidth + 35, viewFrame.size.height);
    }
   	[rightV setFrame:viewFrame]; 
    
    UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	[detailButton addTarget:self action:@selector(calloutButtonPressed:) forControlEvents:UIControlEventTouchDown];
	[detailButton setTag:[delegate flatTag]];
	frame = detailButton.frame;
	frame.origin.x = viewFrame.size.width - 30;
	[detailButton setFrame:frame];
	[rightV addSubview:detailButton];
    
    
	[annView setRightCalloutAccessoryView:rightV];
	[rightV release];
    [priceLabel release];
	
	// Create the left view with the discount image
	
    [annView setLeftCalloutAccessoryView:nil];
	[annView setImage:[UIImage imageNamed:@"poid.png"]];
    
	[annView setCenterOffset:CGPointMake(5, -22)]; // Offset to point the image to the precise position
	[annView setCalloutOffset:CGPointMake(0, 0)]; // Offset to center the callout "point"
	[annView setOpaque:YES];
	
	return annView;
}

- (void)calloutButtonPressed:(id)sender {
	UIButton *button = sender;
	ListFlat *flat = [[_parentVC flats] objectAtIndex:button.tag];
	[_parentVC goToDetail:flat];
}

- (void)returnMyPosition:(id)sender {
    MKCoordinateSpan span = MKCoordinateSpanMake(0.02,0.02);
	CLLocationCoordinate2D myLocation;
	myLocation.latitude  = [[LocationManager sharedInstance] myLocation].coordinate.latitude;
	myLocation.longitude = [[LocationManager sharedInstance] myLocation].coordinate.longitude;
    MKCoordinateRegion myRegion = MKCoordinateRegionMake(myLocation, span);
	[_mapView regionThatFits:myRegion];
    [_mapView setRegion:myRegion animated:YES];

}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
	FlatAnnotation *annotation = view.annotation;
	int position = [_markers indexOfObject:annotation];
    ListFlat *flat = [[_parentVC flats] objectAtIndex:position];
	[_parentVC goToDetail:flat];
	
}

- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error {
	DLog(@"Error Loading map");
	
}

@end
